package info.javatech.jmf.client.controller;

import info.javatech.jmf.client.controller.exceptions.ComponentConstructionException;
import info.javatech.jmf.client.controller.exceptions.UnproperProtocolObjectFormat;
import info.javatech.jmf.client.controller.wsclient.PComponent;
import java.lang.UnsupportedOperationException;
import java.util.Hashtable;

public abstract class JMFAbstractComponentWrapper implements JMFComponentWrapperInterface{
    
    private JMFClientController controller;
    
    private Hashtable componentIdByJ2meComponent;
    
    protected void registerComponentId(PComponent component, Object j2meComponent) throws UnproperProtocolObjectFormat {
        if (component.getId()==null) throw new UnproperProtocolObjectFormat();
        
        componentIdByJ2meComponent.put(j2meComponent,component.getId());
    }
    
    protected String getStoredComponentId(Object j2meComponent) {
        return (String) componentIdByJ2meComponent.get(j2meComponent);
    }
    
    protected JMFClientController getController() {
        return controller;
    }
    
    public void setController(JMFClientController controller) {
        this.controller = controller;
    }
    
    public JMFAbstractComponentWrapper() {
        componentIdByJ2meComponent = new Hashtable();
    }
    
    public final Object constructInstance(PComponent pc) throws ComponentConstructionException {
        Object obj = constructInstanceImplementation(pc);
        
        controller.registerComponent(obj);
        
        try {
            registerComponentId(pc,obj);
        } catch (UnproperProtocolObjectFormat ex) {
            ex.printStackTrace();
        }
        
        return obj;
    }
    
    public Object constructInstanceImplementation(PComponent pc) throws ComponentConstructionException {
        throw new UnsupportedOperationException("Invalid call, call constructInstance instead");
    }
    
    public final PComponent persist(Object obj,PComponent eventSource) {
        PComponent comp = persistImplementation(obj,eventSource);
        
        comp.setId(getStoredComponentId(obj));
        
        return comp;
    }
    
    public PComponent persistImplementation(Object obj,PComponent eventSource) {
        throw new UnsupportedOperationException("Invalid call, call persist instead");
    }
    
    public void beforeNewResponse() {
        componentIdByJ2meComponent.clear();
    }
    
}